package com.af.monitorModule.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.zip.GZIPInputStream;

public class RestUtil {

    /**
     * 检查URL有效性
     * 超时返回false
     * @param url
     * @param seconds
     * @param method
     * @return
     */
    public static boolean checkUrl(String url,int seconds,String method){
        try {
            method = method.toUpperCase();
            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            httpRequestFactory.setConnectionRequestTimeout(1000 * seconds);
            httpRequestFactory.setConnectTimeout(1000 * seconds);
            httpRequestFactory.setReadTimeout(1000 * seconds);
            RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
            switch (method) {
                case "GET": return restTemplate.getForEntity(url, String.class).getStatusCodeValue() == 200;
                case "POST": return restTemplate.postForEntity(url, new JSONObject() ,String.class).getStatusCodeValue() == 200;
                default: return false;
            }
        } catch (Exception e){
            return false;
        }
    }

    /**
     * 请求GET接口请求 restful风格
     * @param url
     * @param resType
     * @param data
     * @param <T>
     * @return
     */
    public static <T> T sendGet(String url, Class<T> resType, Map<String,Object> data){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForEntity(url,resType,data).getBody();
    }
    /**
     * 请求POST接口请求 restful风格
     * @param url
     * @param resType
     * @param data
     * @param <T>
     * @return
     */
    public static <T> T sendPost(String url, Class<T> resType, Map<String,Object> data){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url,data,resType).getBody();
    }

    public static byte[] unGZip(InputStream inputStream) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
                byte[] buf = new byte[4096];
                int len = -1;
                while ((len = gzipInputStream.read(buf, 0, buf.length)) != -1) {
                    byteArrayOutputStream.write(buf, 0, len);
                }
                return byteArrayOutputStream.toByteArray();
            } finally {
                byteArrayOutputStream.close();
            }
        }catch (Exception e){
            return new byte[0];
        }

    }
}
